const {
	$_ULOG,
} = require('../logger/logger')
const {
	getTime,
	getWeekIndex,
} = require('../../utils/dateUtils')
const userDAO = require('../../utils/dao/user-dao')
const {
	encPwd,
	funcVerify,
} = require('../utils')
const Response = require('./Response')

const userLoginFilterPro = async function(req) {
	let uid = req.session._userInfo && req.session._userInfo._id && req.session._uid || ''
	if (!uid)
		return new Response('105', '用户未登录')
	let result = await userDAO.getUserByUid(uid)
	delete req.session._userInfo
	delete req.session._uid
	if (!result || !result._id)
		return new Response('205', '账户不存在')
	req.session._uid = String(result._id)
	req.session._userInfo = result
	return new Response('000', '成功', result)
}

module.exports = {

	Response,

	/**
	 * 判断用户信息
	 * @param  {[type]}   req  [description]
	 * @param  {[type]}   res  [description]
	 * @param  {Function} next [description]
	 * @return {[type]}        [description]
	 */
	userLoginFilter(req, res, next) {
		userLoginFilterPro(req).then(response => {
			if (response.code == '000')
				return next()
			res.type('json').send(response)
		})
	},

	/**
	 * 登录
	 * @param {[type]} params [description]
	 */
	login: async function(req) {
		let params = req.body
		if (!params.username || !params.password)
			return new Response('101', '请求参数错误')
		let result = await userDAO.login({
			username: params.username,
			password: encPwd(params.password),
		})
		if (!result || !result._id)
			return new Response('102', '登录失败')
		result.uid = result._id
		req.session._userInfo = result
		req.session._uid = String(result._id)
		return new Response('000', '成功', result)
	},

	/**
	 * 退出
	 * @param {[type]} params [description]
	 */
	logout: async function(req) {
		// 销毁session
		req.session.destroy(err => {})
		return new Response('000', '成功')
	},

	/**
	 * 用户添加
	 * @param  {[type]} params [description]
	 * @return {[type]}        [description]
	 */
	userAdd: async function(req) {
		if (!funcVerify(req, 'user_add'))
			return new Response('201', '没有权限')
		let user = await userDAO.userAdd(req.body)
		if (user == -1)
			return new Response('202', '用户名已存在')
		return new Response('000', '成功')
	},

	/**
	 * 用户修改
	 * @param  {[type]} req [description]
	 * @return {[type]}     [description]
	 */
	userModify: async function(req) {
		if (!funcVerify(req, 'user_modify'))
			return new Response('201', '没有权限')
		let user = await userDAO.userModify(req.body)
		if (!user || !user._id)
			return new Response('203', '修改失败')
		return new Response('000', '成功')
	},

	userDel: async function(req) {
		if (!funcVerify(req, 'user_del'))
			return new Response('201', '没有权限')
		await userDAO.userDel(req.body)
		return new Response('000', '成功')
	},

	list: async function(req) {
		if (!funcVerify(req, 'user_list'))
			return new Response('201', '没有权限')
		let {
			role_ids,
		} = req.session._userInfo
		return userDAO.list(req.body, role_ids)
	},

}

/**
 * 获取随机昵称
 * @return {[type]} [description]
 */
function getRandomNickName() {
	let nickname = crypto.createHash('md5').update(`${Math.random()}`).digest('hex')
	return Buffer.from(nickname).toString('base64').slice(0, 8)
}

/**
 * 发送验证码
 * @param  {[type]} mobile [description]
 * @return {[type]}        [description]
 */
function getMessageCodeTemplate(mobile, type, session) {
	return new Promise((resolve, reject) => {
		let code = `${Math.random()}`.replace('0.', '').slice(0, 4)
		session.messageInfo = {
			mobile,
			type,
			code,
			time: Date.now(),
		}
		$_ULOG(session.messageInfo)
		resolve(JSON.stringify({
			number: code,
		}))
	});
}

/**
 * 处理验证短信
 * @param  {[type]} req [description]
 * @return {[type]}     [description]
 */
function handleMsgCode(req) {
	let {
		mobile,
		type,
		code,
		time,
	} = req.session.messageInfo
	if (Date.now() - time > 360000) {
		code = ''
		type = ''
	}
	return {
		cacheMsgMobile: mobile,
		cacheMsgCode: code,
		cacheMsgType: type,
	}
}